import sys
import os
import os.path
import zipfile
import imp
import tempfile
import shutil
import re

import mdf.debug as debug
import mdf.config as config
import mdf.writeup as writeup
import mdf.utils as utils
import mdf.bbcode as bbcode


from jinja2 import Environment, PackageLoader, Template, FileSystemLoader, evalcontextfilter, Markup, escape
loader = FileSystemLoader( config.default_template_dir )
env = Environment( loader = loader )

def is_notempty( n ):
	if n != []:
		return True
	return False
env.tests["notempy"] = is_notempty


env.filters['nl2br'] = utils.nl2br

class PackageRepo:
	#pkgdir directory where is all packages that will be used
	def __init__( self, pkgdir, outputdir ):
		self.pkgdir = os.path.abspath( pkgdir )
		#print self.pkgdir
		self.outputdir = os.path.abspath( outputdir )
		self.packages = []
		self.tmpdir = tempfile.mkdtemp()
		for pkgname in self.list_pkgnames():
			pkg = Package( pkgpath=self.pkgdir+"/"+pkgname, tmprepo=self.tmpdir )
			self.packages.append( pkg )
	
	def __del__( self ):
		shutil.rmtree( self.tmpdir )
	
	
	def list_pkgnames( self ):
		ret = []
		dirlist = os.listdir( self.pkgdir )
		for fname in dirlist:
			ret.append( fname )
		return ret
	
	def list_categories( self ):
		ret = []
		for p in self.packages:
			if p.writeup.category not in ret:
				ret.append( p.writeup.category )
		return ret
	
	def list_subcategories( self, category ):
		ret = []
		for p in self.packages:
			if p.writeup.category == category:
				ret.append( p.writeup.subcategory )
		return ret
	
	def render_category_list( self, category ):
		founded = False
		wu = []
		for p in self.packages:
			founded = False
			print p.writeup.category
			if p.writeup.category == category:
				for el in wu:
					if el[0] == p.writeup.subcategory:
						el[1].append( p.writeup )
						founded = True
				if founded == False:
					wu.append([p.writeup.subcategory,[p.writeup]])
		
		#sort by key
		for i in range( 0, len(wu) ):
			wu[i][1] = sorted( wu[i][1], key=lambda title: title.title )
			
		
		templ = env.get_template( "article_list.thtml" )
		f = open( self.outputdir+"/writeup.html" , "w" )
		f.write( templ.render( writeups = wu, category=category ) )
		f.close()
	
	def render_articles( self, category ):
		if not os.path.exists( self.outputdir+"/"+category+"/" ):
			os.mkdir( self.outputdir+"/"+category+"/" )
		for p in self.packages:
			if p.writeup.category == category:
				pkg_files = []
				pkg_images = []
				#create directory and copy files for article downloads
				file_dir = self.outputdir+"/files/"+category+"/"+utils.cnv_to_name( p.writeup.title.lower() )
				if not os.path.exists( file_dir ):
					os.mkdir( file_dir )
				for pf in p.files:
					splited = pf.split("/")
					f_name = splited[-1]
					
					"""
					print "START"
					print pf
					print file_dir+"/"+f_name
					print "END"
					"""
					
					shutil.copyfile( pf, file_dir+"/"+f_name )
					pkg_files.append( ["/files/"+p.writeup.category+"/"+utils.cnv_to_name( p.writeup.title.lower() )+"/"+f_name,f_name, os.path.getsize(file_dir+"/"+f_name)/1024 + 1] )
				
				#create directory and copy files for article images
				image_dir = self.outputdir+"/images/"+category+"/"+utils.cnv_to_name( p.writeup.title.lower() )
				if not os.path.exists( image_dir ):
					os.mkdir( image_dir )
				for pf in p.images:
					splited = pf.split("/")
					i_name = splited[-1]
					
					"""
					print "START"
					print pf
					print image_dir+"/"+f_name
					print "END"
					"""
					
					shutil.copyfile( pf, image_dir+"/"+i_name )
					pkg_images.append( "/images/"+p.writeup.category+"/"+utils.cnv_to_name( p.writeup.title.lower() )+"/"+i_name )
				
				templ = env.get_template( "article.thtml" )
				#create new file for every package
				f = open( self.outputdir+"/"+p.writeup.url, "w" )
				f.write( templ.render( writeup = p.writeup, category=category, files=pkg_files, images=pkg_images ) )
				f.close()
				
				



class Package:
	#give path to package name to extract all archive data
	def __init__( self, pkgpath, tmprepo ):
		print pkgpath
		self.writeup = writeup.WriteUp()
		self.tmprepo = tmprepo
		self.tmppkg = tempfile.mkdtemp( dir=self.tmprepo )
		
		if zipfile.is_zipfile( pkgpath ) == False:
			debug.derror( "This file is not zipfile" )
			return None
		try:
			zippkg = zipfile.ZipFile( pkgpath )
		except:
			debug.derror( "Cannot open zipfile" )
			return None
		
		#zippkg.infolist()
		pkgname = pkgpath.split('/')[len(pkgpath.split('/'))-1]
		pkgname = pkgname[:-4]
		self.article = writeup.WriteUp()
		self.files = []
		self.images = []
		tmpdir = self.tmppkg
		for zipobj in zippkg.infolist():
			fname = zipobj.filename[len(pkgname)+1:]
			#load data from package info file
			if fname == "info.py":
				
				zippkg.extract( zipobj, tmpdir )
				info = imp.load_source( "info", tmpdir+"/"+zipobj.filename )
				
				#load all data in to writeup article
				self.writeup.set_title( info.title )
				self.writeup.set_date( info.date )
				self.writeup.set_category( info.category )
				self.writeup.set_subcategory( info.subcategory ) 
				self.writeup.set_url()

				del info
			
			if fname == "post.txt":
				zippkg.extract( zipobj, tmpdir )
				f = open( tmpdir+"/"+zipobj.filename )
				self.writeup.set_article( f.read() )
				f.close()
			
			if fname == "links.py":
				zippkg.extract( zipobj, tmpdir )
				links = imp.load_source( "info", tmpdir+"/"+zipobj.filename )
				
				#load all data in to writeup article
				self.writeup.set_links( links.links )

				del links
			
			if fname[0:6] == "files/":
				zippkg.extract( zipobj, tmpdir )
				if not os.path.isdir( tmpdir+"/"+zipobj.filename ):
					self.files.append( tmpdir+"/"+zipobj.filename )
			
			if fname[0:4] == "img/":
				zippkg.extract( zipobj, tmpdir )
				if not os.path.isdir( tmpdir+"/"+zipobj.filename ):
					self.images.append( tmpdir+"/"+zipobj.filename )
		"""
		print "START--------"
		print self.files
		print self.images
		print "END----------"
		"""

	def list_of_files( self ):
		return self.files
	
	def list_of_images( self ):
		return self.images

	def render( self ):
		pass
		
